package chatdialogservicelogic

import (
	"context"

	dialogmodel "paper-pro/app/chat/model/chatdialog"
	"paper-pro/app/chat/rpc/internal/svc"
	"paper-pro/app/chat/rpc/pb"
	"paper-pro/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLogic {
	return &GetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetLogic) Get(in *pb.ChatDialogGetReq) (*pb.ChatDialogGetResp, error) {
	dialog, err := l.svcCtx.ChatDialogModel.FindOne(l.ctx, in.Id, in.UserId)
	if err != nil && err != dialogmodel.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"获取ID: %s Chat Dialog失败，err: %v", in.Id, err)
	}
	if dialog == nil {
		return nil, errors.Wrapf(ErrDialogNoExistsError, "Get Chat Dialog ID:%s", in.Id)
	}

	var respDialog pb.ChatDialog
	err = copier.Copy(&respDialog, &dialog)
	if err != nil {
		l.Errorf("Get Chat Dialog ID: %s 数据转换失败，error: %v", in.Id, err)
	}
	respDialog.Id = dialog.ID.Hex()
	respDialog.AssistantId = dialog.AssistantId.Hex()

	return &pb.ChatDialogGetResp{
		Dialog: &respDialog,
	}, nil
}
